<template>
  <div class="user-manager">
    <div class="page-header">
      <h1 class="page-title">用户管理</h1>
      <p class="page-subtitle">管理系统用户信息</p>

      <!-- 搜索区域 -->
      <div class="search-section">
        <a-form layout="inline" :model="searchForm" @finish="handleSearch">
          <a-form-item label="用户名">
            <a-input
              v-model:value="searchForm.username"
              placeholder="请输入用户名"
              allow-clear
              style="width: 200px"
            />
          </a-form-item>
          <a-form-item label="角色">
            <a-select
              v-model:value="searchForm.role"
              placeholder="请选择角色"
              allow-clear
              style="width: 150px"
            >
              <a-select-option value="user">普通用户</a-select-option>
              <a-select-option value="admin">管理员</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button style="margin-left: 8px" @click="handleReset"> 重置</a-button>
          </a-form-item>
        </a-form>
      </div>

      <a-divider />

      <!-- 操作按钮区域 -->
      <div class="action-section">
        <a-button type="primary" @click="showAddModal">
          <template #icon>
            <PlusOutlined />
          </template>
          新增用户
        </a-button>
      </div>


      <!-- 表格区域 -->
      <div class="table-section">
        <a-table
          :columns="columns"
          :data-source="tableData"
          :loading="loading"
          :pagination="pagination"
          row-key="id"
          @change="handleTableChange"
        >
          <!-- 头像列 -->
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'avatar'">
              <a-avatar :src="record.avatar" :size="40">
                {{ record.username?.charAt(0)?.toUpperCase() }}
              </a-avatar>
            </template>

            <!-- 角色列 -->
            <template v-else-if="column.key === 'role'">
              <a-tag :color="record.role === 'admin' ? 'red' : 'blue'">
                {{ record.role === 'admin' ? '管理员' : '普通用户' }}
              </a-tag>
            </template>

            <!-- 创建时间列 -->
            <template v-else-if="column.key === 'createTime'">
              {{ formatDate(record.createTime) }}
            </template>

            <!-- 操作列 -->
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="showEditModal(record)"> 编辑</a-button>
                <a-button type="link" size="small" danger @click="showDeleteModal(record)">
                  删除
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 新增/编辑用户模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :confirm-loading="modalLoading"
      width="600px"
      okText="确认"
      cancelText="取消"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
        @finish="handleModalOk"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="用户名" name="username">
              <a-input v-model:value="formData.username" placeholder="请输入用户名" />
            </a-form-item>
          </a-col>
          <a-col :span="12" v-if="!isEdit">
            <a-form-item label="账号" name="account">
              <a-input v-model:value="formData.account" placeholder="请输入账号" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="角色" name="role">
              <a-select v-model:value="formData.role" placeholder="请选择角色">
                <a-select-option value="user">普通用户</a-select-option>
                <a-select-option value="admin">管理员</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="头像" name="avatar">
              <a-input v-model:value="formData.avatar" placeholder="请输入头像URL" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="个人简介" name="profile" v-if="isEdit">
          <a-textarea v-model:value="formData.profile" placeholder="请输入个人简介" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 删除确认模态框 -->
    <a-modal
      v-model:open="deleteModalVisible"
      title="确认删除"
      @ok="handleDelete"
      @cancel="deleteModalVisible = false"
      :confirm-loading="deleteLoading"
      okText="确认"
      cancelText="取消"
    >
      <p>确定要删除用户 "{{ currentUser?.username }}" 吗？此操作不可恢复。</p>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined } from '@ant-design/icons-vue'
import { addUser, deleteUser, listUserVoByPage, updateUser } from '@/api/userController'

// 定义组件名称
defineOptions({
  name: 'UserManager',
})

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 180,
  },
  {
    title: '头像',
    dataIndex: 'avatar',
    key: 'avatar',
    width: 80,
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
    width: 180,
  },
  {
    title: '角色',
    dataIndex: 'role',
    key: 'role',
    width: 100,
  },
  {
    title: '个人简介',
    dataIndex: 'profile',
    key: 'profile',
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right',
  },
]

// 响应式数据
const loading = ref(false)
const tableData = ref<API.UserVO[]>([])
const modalVisible = ref(false)
const modalLoading = ref(false)
const deleteModalVisible = ref(false)
const deleteLoading = ref(false)
const currentUser = ref<API.UserVO | null>(null)
const isEdit = ref(false)

// 搜索表单
const searchForm = reactive<API.UserQueryRequest>({
  current: 1,
  pageSize: 10,
  username: '',
  role: '',
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
})

// 表单数据
const formData = reactive<API.UserAddRequest>({
  username: '',
  account: '',
  avatar: '',
  role: 'user',
})

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
}

// 计算属性
const modalTitle = computed(() => (isEdit.value ? '编辑用户' : '新增用户'))

// 表单引用
const formRef = ref()

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const res = await listUserVoByPage(searchForm)
    if (res.code === 0 && res.data) {
      tableData.value = res.data.records || []
      pagination.total = Number(res.data.total) || 0
      pagination.current = Number(res.data.current) || 1
      pagination.pageSize = Number(res.data.size) || 10
    }
  } catch (error) {
    message.error('获取用户列表失败,' + error.message)
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  searchForm.current = 1
  fetchUserList()
}

// 重置搜索
const handleReset = () => {
  searchForm.username = ''
  searchForm.role = ''
  searchForm.current = 1
  fetchUserList()
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  searchForm.current = pag.current
  searchForm.pageSize = pag.pageSize
  fetchUserList()
}

// 显示新增模态框
const showAddModal = () => {
  isEdit.value = false
  resetFormData()
  modalVisible.value = true
}

// 显示编辑模态框
const showEditModal = (record: API.UserVO) => {
  isEdit.value = true
  currentUser.value = record
  Object.assign(formData, {
    id: record.id,
    username: record.username,
    account: record.username, // 编辑时账号显示为用户名
    avatar: record.avatar,
    role: record.role,
    profile: record.profile,
  })
  modalVisible.value = true
}

// 显示删除模态框
const showDeleteModal = (record: API.UserVO) => {
  currentUser.value = record
  deleteModalVisible.value = true
}

// 模态框确认
const handleModalOk = async () => {
  try {
    await formRef.value?.validate()
    modalLoading.value = true

    if (isEdit.value) {
      // 编辑用户
      const res = await updateUser(formData as API.UserUpdateRequest)
      if (res.code === 0) {
        message.success('用户更新成功')
        modalVisible.value = false
        fetchUserList()
      }
    } else {
      // 新增用户
      const res = await addUser(formData)
      if (res.code === 0) {
        message.success('用户添加成功')
        modalVisible.value = false
        fetchUserList()
      }
    }
  } catch (error) {
    message.error('表单验证失败,' + error.message)
  } finally {
    modalLoading.value = false
  }
}

// 模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
  resetFormData()
}

// 删除用户
const handleDelete = async () => {
  if (!currentUser.value?.id) return

  deleteLoading.value = true
  try {
    const res = await deleteUser({ id: currentUser.value.id })
    if (res.code === 0) {
      message.success('用户删除成功')
      deleteModalVisible.value = false
      fetchUserList()
    }
  } catch (error) {
    message.error('删除失败,' + error.message)
  } finally {
    deleteLoading.value = false
  }
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: undefined,
    username: '',
    account: '',
    avatar: '',
    role: 'user',
    profile: '',
  })
  formRef.value?.resetFields()
}

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>

.user-manager{
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.search-section {
  padding: 16px 16px 0 0;
  margin-bottom: 8px;
}

.action-section {
  padding: 16px;
  margin-bottom: 8px;
}

.table-section {
  overflow: hidden;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 500;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f5f5f5;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
}

:deep(.ant-modal-header) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-modal-footer) {
  border-top: 1px solid #f0f0f0;
}
</style>
